package com.optserso.camera.server.impl;
import com.optserso.camera.server.IRCameraServer;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: fei.li02
 * @Date: 2023/11/16 10:41
 * @Description:红外摄像机服务类
 */
@Service
public class IRCameraServerImpl implements IRCameraServer {
    private static final Logger logger = LoggerFactory.getLogger(IRCameraServerImpl.class);
    public Map<String,Object> ImageStatisticInfo(){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpHost targetHost = new HttpHost("192.168.1.100", 80);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials("User", "Passwd"));
        HttpContext context = new BasicHttpContext();
        context.setAttribute(HttpClientContext.CREDS_PROVIDER, credsProvider);
        HttpPost httpPost = new HttpPost("http://192.168.1.100/cgi-bin/control?Subject=User&Operation=Login");
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf8");
        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("User", "admin"));
        nvps.add(new BasicNameValuePair("Passwd", "admin"));
        nvps.add(new BasicNameValuePair("Type", "Admin"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps, Consts.UTF_8);
        httpPost.setEntity(entity);
        CloseableHttpResponse responseLogin = null;
        CloseableHttpResponse responseImageInfo = null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            responseLogin = httpClient.execute(targetHost, httpPost, context);
            // 打印响应状态
            System.out.println(responseLogin.getStatusLine());
            HttpPost httpImagePost = new HttpPost("http://192.168.1.100/cgi-bin/control?Subject=IRImage&cmd=StatInfo");
            httpImagePost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf8");
            responseImageInfo = httpClient.execute(httpImagePost);
            HttpEntity responseImageInfoEntity = responseImageInfo.getEntity();
            logger.info("登录响应状态为:" + responseImageInfo.getStatusLine());
            if (responseImageInfoEntity != null) {
                map.put("resStatus",responseImageInfo.getStatusLine());
                // URL解码
                String decodedString = URLDecoder.decode(EntityUtils.toString(responseImageInfoEntity), "UTF-8");
                String [] imageInfoStrArr = decodedString.split("&");
                Map<String,Object> imageInfoMap = new HashMap<>();
                for(String imageStrInfo : imageInfoStrArr){
                    String[] imageInfo = imageStrInfo.split("=");
                    String imageKey = imageInfo[0];
                    String imageVal = imageInfo[1];
                    if("Data".equals(imageKey)){
                        imageVal = imageVal.replace("OK\r\n","");
                    }
                    imageInfoMap.put(imageKey,imageVal);
                }
                map.put("imageInfo",imageInfoMap);
            }
            // 关闭响应
            if(responseImageInfo != null){
                responseImageInfo.close();
                logger.info("responseImageInfo已关闭");
            }
            if(responseLogin != null){
                responseLogin.close();
                logger.info("responseLogin已关闭");
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
        }finally {
            // 关闭HttpClient
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
        return map;
    }
}
